<?php
if(!interface_exists('XErrorHandler', false)){
	require(dirname(__FILE__).DIRECTORY_SEPARATOR.'XErrorHandler.php');
}
class XBasicErrorHandler implements XErrorHandler{
	protected static $LEVELS = array(		
		E_CORE_ERROR => "E_CORE_ERROR", 
		E_CORE_WARNING => "E_CORE_WARNING", 
		E_COMPILE_ERROR => "E_COMPILE_ERROR", 
		E_COMPILE_WARNING => "E_COMPILE_WARNING", 
		E_ERROR => "E_ERROR", 
		E_NOTICE => "E_NOTICE", 
		E_PARSE => "E_PARSE", 
		E_USER_ERROR => "E_USER_ERROR", 
		E_USER_NOTICE => "E_USER_NOTICE",
		E_USER_WARNING => "E_USER_WARNING", 
		E_WARNING => "E_WARNING",
	);
	
	protected static $EVENTS = array(		
		E_CORE_ERROR => ERROR, 
		E_CORE_WARNING => WARN, 
		E_COMPILE_ERROR => ERROR, 
		E_COMPILE_WARNING => WARN, 
		E_ERROR => ERROR, 
		E_NOTICE => WARN, 
		E_PARSE => WARN, 
		E_USER_ERROR => ERROR,
		E_USER_NOTICE => WARN,
		E_USER_WARNING => WARN, 
		E_WARNING => ERROR,
	);	
	
	protected static $TYPES = array(		
		E_CORE_ERROR => "FATAL ERROR", 
		E_CORE_WARNING => "WARNING", 
		E_COMPILE_ERROR => "COMPILE ERROR", 
		E_COMPILE_WARNING => "COMPILE WARNING", 
		E_ERROR => "FATAL ERROR", 
		E_NOTICE => "NOTICE",
		E_PARSE => "PARSE ERROR", 
		E_USER_ERROR => "FATAL ERROR", 
		E_USER_NOTICE => "NOTICE",
		E_USER_WARNING => "WARNING", 
		E_WARNING => "WARNING",
	);
	
	public function handle($errno, $errstr, $errfile, $errline, $errcontext){
		if(!isset(self::$LEVELS[$errno])){
			return false;
		}
		//log first
		XEventContext::singleton()->publish(new XLoggingEvent($this, self::$EVENTS[$errno], $errstr));
		//redirect
		$redirection = XConfig::singleton()->get("project.error.{$errno}.redirect");
		if(is_string($redirection)){
			XServletResponse::singleton()->redirect($redirection);
		}
		//load user error html
		//load default error html
		foreach(array(
			PROJECT_ROOT.'/config/error',
			dirname(__FILE__).'/page',
			) as $dir){
			if($this->_html($dir, $errno, $errstr, $errfile, $errline, $errcontext)){
				return true;
			}
		}
		return false;	
	}
	
	public function _html($dir, $errno, $errstr, $errfile, $errline, $errcontext){
		$file = $dir.'/error.default';	
		if(!file_exists($file)){
			return false;
		}
		$html = file_get_contents($file);
		$html = str_replace('%{type}', self::$TYPES[$errno], $html);
		$html = str_replace('%{err}', self::$LEVELS[$errno], $html);
		$html = str_replace('%{errstr}', $errstr, $html);
		$html = str_replace('%{errfile}', $errfile, $html);
		$html = str_replace('%{errline}', $errline, $html);
		echo $html;
		return true;		
	}
}
?>